const express=require("express");
const app=express();
const port=3001;
const db=require("./db/11_test_db");
app.get("/:id",function(req,res,next){
    let bookId=parseInt(req.params.id);
    if(Number.isNaN(bookId)){
        next();
    }else{
        db.query("select * from books where id=?",[bookId]).then(result=>{
            console.log(result);
            res.json(result);
        }).catch(error=>{
            console.log(error);
            res.end();
        });
    }
});
app.get("/",function(req,res,next){
    
    db.query("select * from books").then((result)=>{

        console.log(result);
        res.json(result);
    }).catch(error=>{
        console.log(error);
        res.end();
    });
   
});

app.post("/",function(req,res,next){
    let title="测试书籍信息"+new Date().toLocaleString();
    db.query("INSERT into books(title,description) values(?,?)",[title,"作者：赵六",]).then((result)=>{

        console.log(result);
        res.json(result);
    }).catch(error=>{
        console.log(error);
        res.end();
    });
   
});
app.put("/:id",function(req,res,next){
    let bookId=parseInt(req.params.id);
    if(Number.isNaN(bookId)){
        next();
    }else{
        let title="测试书籍信息"+new Date().toLocaleString();
        db.query("update books set title=?,description=? where id=?",[title,"作者：陈三"]).then(result=>{
            console.log(result);
            res.json(result);
        }).catch(error=>{
            console.log(error);
            res.end();
        });
    }
});
app.delete("/:id",function(req,res,next){
    let bookId=parseInt(req.params.id);
    if(Number.isNaN(bookId)){
        next();
    }else{
        
        db.query("delete from books where id=?",[bookId]).then(result=>{
            console.log(result);
            res.json(result);
        }).catch(error=>{
            console.log(error);
            res.end();
        });
    }
});
app.listen(port,function(){
    console.log(`MyApp访问地址:http://127.0.0.1:${port}`);
});